<?PHP
/*
 * Copyright 2008 by Oliver Radwan, Maxwell Palmer, Nolan McNair,
 * Taylor Talmage, and Allen Tucker.  This program is part of RMH Homebase.
 * RMH Homebase is free software.  It comes with absolutely no warranty.
 * You can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation
 * (see <http://www.gnu.org/licenses/ for more information).
*/
/*
 *	personEdit.php
 *  oversees the editing of a person to be added, changed, or deleted from the database
 *	@author Oliver Radwan and Allen Tucker
 *	@version 9/1/2008
 */
	session_start();
	session_cache_expire(30);
    include_once('database/dbPersons.php');
    include_once('database/Person.php');
    include_once('database/dbLog.php');
	$id = $_GET["id"];
	if ($id=='new') {
	 	     $person = new Person('new','applicant',null,null,null,null,null,null,null,null,
	 	        null,null,null,null,null,null,null,null,null,null,null,null,null,
                null,null,null,md5('new'));
	}
	else {
		$query_result = get_person($id);
	    if ($query_result) {
	         $dbP = mysql_fetch_array($query_result, MYSQL_ASSOC);
	         $person = new Person($dbP['first_name'], $dbP['last_name'], $dbP['address'], $dbP['city'], $dbP['state'], $dbP['zip'],
								 $dbP['phone1'], $dbP['phone2'], $dbP['email'], $dbP['type'],
                                 $dbP['background_check'], $dbP['interview'], $dbP['shadow'],
                                 $dbP['convictions'], $dbP['wherelived'], $dbP['experience'], $dbP['motivation'], $dbP['specialties'],
                                 $dbP['availability'], $dbP['schedule'], $dbP['history'],
                                 $dbP['birthday'],
                                 $dbP['start_date'],
                                 $dbP['public_notes'], $dbP['my_notes'], $dbP['private_notes'], $dbP['password']);
	    }
	    else {
             echo('<p id="error">Error: there\'s no person with this id in the database</p>');
		     die();
        }
	}
?>
<html>
	<head>
		<title>
			Editing <?PHP echo($person->get_first_name()." ".$person->get_last_name());?>
		</title>
		<link rel="stylesheet" href="styles.css" type="text/css" />
	</head>
<body>
  <div id="container">
    <?PHP include('header.php');?>
	<div id="content">
<?PHP
	include('personValidate.inc');
	if($_POST['_form_submit']!=1)
	//in this case, the form has not been submitted, so show it
		include('personForm.inc');
	else {
	//in this case, the form has been submitted, so validate it
		$errors = validate_form(); 	//step one is validation.
									// errors array lists problems on the form submitted
		if ($errors) {
		// display the errors and the form to fix
			show_errors($errors);
			if ($_POST['availability']==null)
			   $ima = null;
			else $ima = implode(',',$_POST['availability']);
			$person = new Person($_POST['first_name'], $_POST['last_name'], $_POST['address'], $_POST['city'], $_POST['state'], $_POST['zip'],
								 $_POST['phone1'], $_POST['phone2'], $_POST['email'], implode(',',$_POST['type']),
                                 $_POST['background_check'], $_POST['interview'], $_POST['shadow'],
                                 $_POST['convictions'], $_POST['wherelived'], $_POST['experience'], $_POST['motivation'], $_POST['specialties'],
                                 $ima, $_POST['schedule'], $_POST['history'],
                                 $birthday,
                                 $start_date,
                                 $_POST['public_notes'], $_POST['my_notes'], $_POST['private_notes'], $_POST['old_pass']);
			include('personForm.inc');
		}
		// this was a successful form submission; update the database and exit
		else
			process_form($id);
		include('footer.inc');
		echo('</div></div></body></html>');
		die();
	}
	include('footer.inc');

/**
* process_form sanitizes data, concatenates needed data, and enters it all into a database
*/
function process_form($id)	{
	//step one: sanitize data by replacing HTML entities and escaping the ' character
		$first_name = trim(str_replace('\\\'','',htmlentities($_POST['first_name'])));
		$last_name = trim(str_replace('\\\'','\'',htmlentities($_POST['last_name'])));
		$address = trim(str_replace('\\\'','\'',htmlentities($_POST['address'])));
		$city = trim(str_replace('\\\'','\'',htmlentities($_POST['city'])));
		$state = trim(htmlentities($_POST['state']));
		$zip = trim(htmlentities($_POST['zip']));
		$phone1 = trim(str_replace(' ','',htmlentities($_POST['phone1'])));
		$clean_phone1 = ereg_replace("[^0-9]", "", $phone1);
		$phone2 = trim(str_replace(' ','',htmlentities($_POST['phone2'])));
		$clean_phone2 = ereg_replace("[^0-9]", "", $phone2);

		$private_notes = trim(str_replace('\\\'','\'',htmlentities($_POST['private_notes'])));
		$public_notes = trim(str_replace('\\\'','\'',htmlentities($_POST['public_notes'])));
		$my_notes = trim(str_replace('\\\'','\'',htmlentities($_POST['my_notes'])));

		$background_check = '';
		$shadow = '';
		$interview = '';
		if($_POST['background_check']=='yes') $background_check = 'yes';
		if($_POST['interview']=='yes') $interview = 'yes';
		if($_POST['shadow']=='yes') $shadow = 'yes';

		$convictions = trim(str_replace('\\\'','\'',htmlentities($_POST['convictions'])));
		$wherelived = trim(str_replace('\\\'','\'',htmlentities($_POST['wherelived'])));
		$experience = trim(str_replace('\\\'','\'',htmlentities($_POST['experience'])));
		$motivation = trim(str_replace('\\\'','\'',htmlentities($_POST['motivation'])));
		$specialties = trim(str_replace('\\\'','\'',htmlentities($_POST['specialties'])));

	//concatenate birthday and start_date strings
		if($_POST['DateOfBirth_Year']=="")
				$birthday = $_POST['DateOfBirth_Month'].'-'.$_POST['DateOfBirth_Day'].'-XX';
		else
				$birthday = $_POST['DateOfBirth_Month'].'-'.$_POST['DateOfBirth_Day'].'-'.$_POST['DateOfBirth_Year'];
		if (strlen($birthday) < 8) $birthday = '';
		$start_date = $_POST['DateOfStart_Month'].'-'.$_POST['DateOfStart_Day'].'-'.$_POST['DateOfStart_Year'];
        if (strlen($start_date) < 8) $start_date = '';
		$email = $_POST['email'];

	// comma-separated list of person types 'applicant', 'volunteer', 'sub', etc.
		if ($_SESSION['access_level']==0 && !in_array('applicant',$_POST['type']))
				$_POST['type'][] = 'applicant';
		$type = implode(',', $_POST['type']);
		if ($_POST['availability'] != null)
			$availability=implode(',', $_POST['availability']);
		else $availability = "";

	// these two are not visible for editing, so they go in and out unchanged
		$schedule = $_POST['schedule'];
		$history = $_POST['history'];

	//step two: try to make the deletion, password change, addition, or change
		if($_POST['deleteMe']=="DELETE"){
			$result = get_person($id);
			if (!$result)
				echo('<p>Unable to delete. ' .$first_name.' '.$last_name. ' is not in the database. <br>Please report this error to the House Manager.');
			else {
				//What if they're the last remaining manager account?
				if(strpos($type,'manager')!==false){
				//They're a manager, we need to check that they can be deleted
					$managers = getall_type('manager');
					if (!$managers || mysql_num_rows($managers) <= 1)
						echo('<p class="error">You cannot remove the last remaining manager from the database.</p>');
					else {
						$result = remove_person($id);
						echo("<p>You have successfully removed " .$first_name." ".$last_name. " from the database.</p>");
						if($id==$_SESSION['_id']){
							session_unset();
							session_destroy();
						}
					}
				}
				else {
					$result = remove_person($id);
					echo("<p>You have successfully removed " .$first_name." ".$last_name. " from the database.</p>");
					if($id==$_SESSION['_id']){
						session_unset();
						session_destroy();
					}
				}
			}
		}

		// try to reset the person's password
		else if($_POST['reset_pass']=="RESET"){
				$id = $_POST['old_id'];
				$result = remove_person($id);
				$pass = $first_name . $phone1;
                $newperson = new Person($first_name, $last_name, $address, $city, $state, $zip, $clean_phone1, $clean_phone2, $email, $type,
                		$background_check, $interview, $shadow, $convictions, $wherelived, $experience, $motivation, $specialties,
                		$availability, $schedule, $history,
                		$birthday, $start_date,
                		$public_notes, $my_notes, $private_notes, $pass);
                $result = add_person($newperson);
				if (!$result)
                   echo ('<p class="error">Unable to reset ' .$first_name.' '.$last_name. "'s password.. <br>Please report this error to the House Manager.");
				else echo("<p>You have successfully reset " .$first_name." ".$last_name. "'s password.</p>");
		}

		// try to add a new person to the database
		else if ($_POST['old_id']=='new') {
			    $id = $first_name.$clean_phone1;
				//check if there's already an entry
				$dup = get_person($id);
				if ($dup)
					echo('<p class="error">Unable to add ' .$first_name.' '.$last_name. ' to the database. <br>Another person with the same id is already there.');
				else {
					$newperson = new Person($first_name, $last_name, $address, $city, $state, $zip, $clean_phone1, $clean_phone2, $email, $type,
                                             $background_check, $interview, $shadow, $convictions, $wherelived, $experience, $motivation, $specialties,
                                             $availability, $schedule, $history,
                                             $birthday, $start_date,
                                             $public_notes, $my_notes, $private_notes, $id );
                    $result = add_person($newperson);
					if (!$result)
                        echo ('<p class="error">Unable to add " .$first_name." ".$last_name. " in the database. <br>Please report this error to the House Manager.');
					else if ($_SESSION['access_level']==0)
							 echo("<p>Your application has been successfully submitted.<br>  The House Manager will contact you soon.  Thank you!");
						 else echo("<p>You have successfully added " .$first_name." ".$last_name. " to the database.</p>");
				}
		}

		// try to replace an existing person in the database by removing and adding
		else {
				$id = $_POST['old_id'];
				$pass = $_POST['old_pass'];
				$result = remove_person($id);
                if (!$result)
                   echo ('<p class="error">Unable to update ' .$first_name.' '.$last_name. '. <br>Please report this error to the House Manager.');
				else {
					$newperson = new Person($first_name, $last_name, $address, $city, $state, $zip, $clean_phone1, $clean_phone2, $email, $type,
                        $background_check, $interview, $shadow,$convictions, $wherelived, $experience, $motivation, $specialties,
                        $availability, $schedule, $history,
                        $birthday, $start_date,
                        $public_notes, $my_notes, $private_notes, $pass);
                	$result = add_person($newperson);
					if (!$result)
                   		echo ('<p class="error">Unable to update ' .$first_name.' '.$last_name. '. <br>Please report this error to the House Manager.');
					else echo("<p>You have successfully edited " .$first_name." ".$last_name. " in the database.</p>");
					add_log_entry('<a href=\"viewPerson.php?id='.$id.'\">'.$first_name.' '.$last_name.'</a>\'s Personnel Edit Form has been changed. ' .
							'(Check <a href=\"personEdit.php?id='.$id.'\">that form</a> for new Notes to you.)');
				}
		}
}
?>
    </div>
  </div>
</body>
</html>
